package cn.fl.settlement.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.EncryptUtil;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.api.ICapCstSettleApiService;
import cn.fl.capital.condition.CapCstStmApplyQC;
import cn.fl.capital.condition.CapCstStmScheduleQC;
import cn.fl.capital.constant.SettleConstant;
import cn.fl.capital.dto.CapCstStmApplyDTO;
import cn.fl.capital.dto.CapCstStmScheduleDTO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.condition.PrjPrdPaySchMQueryCondition;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.settle.api.ISettleBackstageApiService;
import cn.fl.settle.condition.PrjStlTripleRcdQC;
import cn.fl.settle.dto.PrjStlRfdRcdDTO;
import cn.fl.settle.dto.PrjStlTripleRcdDTO;
import cn.fl.settlement.service.ISettlementService;
import cn.fl.settlement.transform.CapCstStmApplyVOTransform;
import cn.fl.settlement.transform.CapCstStmScheduleVOTransform;
import cn.fl.settlement.transform.PrjStlTripleRcdVOTransform;
import cn.fl.settlement.vo.CapCstStmApplyVO;
import cn.fl.settlement.vo.CapCstStmScheduleVO;
import cn.fl.settlement.vo.PrjStlTripleRcdVO;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 结清申请表 客户端服务层接口
 * @Author: judahan
 * @CreateDate: 2019/3/12 16:32
 * @Version: 1.0
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class SettlementServiceImpl implements ISettlementService {

    /**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(SettlementServiceImpl.class);

    @Autowired
    private ICapCstSettleApiService capCstSettleApiService;

    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

    @Autowired
    private ISettleBackstageApiService settleBackstageApiService;

    /**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        CapCstStmApplyQC condition = null;
        if (null == page) {
            page = new Pager();
            page.setCondition(new CapCstStmApplyQC());
        }
        condition = (CapCstStmApplyQC) page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        page = this.capCstSettleApiService.searchListPage(page);
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            List<CapCstStmApplyVO> voList = CapCstStmApplyVOTransform.toVOList((List<CapCstStmApplyDTO>) page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
    }

    /**
     * 按进度序号升序查询客户结清处理进度
     *
     * @param capCstStmScheduleQC
     * @return
     */
    @Override
    public List<CapCstStmScheduleVO> selectCapCstStmScheduleByCondition(CapCstStmScheduleQC capCstStmScheduleQC) {
        List<CapCstStmScheduleVO> capCstStmScheduleVOList = new ArrayList<>();
        List<CapCstStmScheduleDTO> capCstStmScheduleDTOList = capCstSettleApiService.selectCapCstStmScheduleByCondition(capCstStmScheduleQC);

        if(capCstStmScheduleDTOList != null && capCstStmScheduleDTOList.size() > 0) {
            capCstStmScheduleVOList = CapCstStmScheduleVOTransform.toVOList(capCstStmScheduleDTOList);
        }
        return capCstStmScheduleVOList;
    }

    /**
     * 根据“结清申请记录id”查询结清申请信息
     * @param id 结清申请记录id
     * @return
     */
    @Override
    public CapCstStmApplyDTO selectById(Long id) {
        return capCstSettleApiService.selectById(id);
    }

    @Override
    public List<CapCstStmApplyDTO> searchList(CapCstStmApplyQC capCstStmApplyQC) throws BaseException {
        return capCstSettleApiService.searchList(capCstStmApplyQC);
    }

    @Override
    public CapCstStmApplyDTO queryByPaySchIdAndProcId(Long paySchId, String procInsId) throws BaseException {
        CapCstStmApplyDTO capCstStmApplyDTO = new CapCstStmApplyDTO();

        CapCstStmApplyQC capCstStmApplyQC = new CapCstStmApplyQC();
        capCstStmApplyQC.setPaySchId(paySchId);
        capCstStmApplyQC.setProcId(procInsId);
        capCstStmApplyQC.setIsDel(BaseConstant.IS_YESNO_NO);

        List<CapCstStmApplyDTO> capCstStmApplyDTOS = capCstSettleApiService.searchList(capCstStmApplyQC);
        if (CollectionUtils.isNotEmpty(capCstStmApplyDTOS)) {
            capCstStmApplyDTO = capCstStmApplyDTOS.get(0);
        }
        return capCstStmApplyDTO;
    }

    /**
     * 添加数据字典名称
     *
     * @param voList
     */
    public void setDictData(List<CapCstStmApplyVO> voList) {
        if (CollectionUtils.isEmpty(voList)) return;
        Map<String, String> isRefundMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_SYS_YES_NO_CD);
        Map<String, String> stsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), SettleConstant.CODE_STM_APPLY_CD);

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (CapCstStmApplyVO vo : voList) {
            if (isRefundMap != null && isRefundMap.containsKey(String.valueOf(vo.getIsRefund()))) {
                vo.setIsRefundNm(isRefundMap.get(String.valueOf(vo.getIsRefund())));
            }
            if (stsCdMap != null && stsCdMap.containsKey(vo.getStsCd())) {
                vo.setStsCdNm(stsCdMap.get(vo.getStsCd()));
            }
            if(vo.getCrtTm() != null) {
                vo.setCrtTmNm(simpleDateFormat.format(vo.getCrtTm()));
            }
            if (vo.getMdfTm() != null) {
                vo.setMdfTmNm(simpleDateFormat.format(vo.getMdfTm()));
            }
        }
    }

    @Override
    public Map<String, Object> trialSettleIRRData(String paySchNo, Long stlAmt, Date date) throws BaseException {
        PrjPrdPaySchMQueryCondition condition = new PrjPrdPaySchMQueryCondition();
        condition.setPaySchNo(paySchNo);
        List<PrjPrdPaySchMDTO> paySchMDTOS = prjPrdPaySchMApiService.selectPaySchMByPaySchNo(condition);
        if (CollectionUtils.isEmpty(paySchMDTOS)) {
            throw new BaseException(paySchNo + "支付表数据不存在！");
        }
        Long paySchId = paySchMDTOS.get(0).getId();
        return prjPrdPaySchMApiService.getCalcStlCstIRRAndDiscountForTrial(paySchId, stlAmt, date);
    }

    @Override
    public Pager searchAutoRefundListPage(Pager page) throws BaseException {
        if (null == page) {
            page = new Pager();
            page.setCondition(new CapCstStmApplyQC());
        }
        page = settleBackstageApiService.searchAutoRefundListPage(page);
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            translateDictData((List<PrjStlRfdRcdDTO>) page.getResultList());
        }
        return page;
    }

    @Override
    public PrjStlRfdRcdDTO selectAutoRefundById(Long id) throws BaseException {
        if (id == null) {
            return null;
        }
        return settleBackstageApiService.selectRefundById(id);
    }

    @Override
    public Pager searchStlTripleListPage(Pager page) throws BaseException {
        if (null == page) {
            page = new Pager();
            page.setCondition(new PrjStlTripleRcdQC());
        }
        page = settleBackstageApiService.searchStlTripleListPage(page);
        List<PrjStlTripleRcdVO> resultList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            Map<String, String> stsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), SettleConstant.TP_STL_STS_CD);
            List<PrjStlTripleRcdDTO> dtoList = (List<PrjStlTripleRcdDTO>) page.getResultList();

            for (PrjStlTripleRcdDTO dto : dtoList) {
                PrjStlTripleRcdVO vo = PrjStlTripleRcdVOTransform.toVO(dto);
                if (vo.getStsCd() != null) {
                    vo.setStsCdNm(stsCdMap.get(vo.getStsCd().toString()));
                }
                resultList.add(vo);
            }
        }
        page.setResultList(resultList);
        return page;
    }

    /**
     * 翻译字典数据
     * @param list
     */
    private void translateDictData(List<PrjStlRfdRcdDTO> list) {
        Map<String, String> stsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), SettleConstant.REFUND_STS_CD);
        if (CollectionUtils.isMapEmpty(stsCdMap)) {
            return;
        }
        for (PrjStlRfdRcdDTO dto : list) {
            if (stsCdMap.containsKey(dto.getStsCd().toString())) {
                dto.setStsCdNm(stsCdMap.get(dto.getStsCd().toString()));
            }
            dto.setSignNo("");
            dto.setActNm("");
            dto.setActNo("");
            dto.setIdentityNo("");
            dto.setActTel("");
        }
    }
}
